package com.example.smartclassroom.config;

import ch.qos.logback.core.util.StringUtil;
import com.example.smartclassroom.entity.dto.LoginDTO;
import com.example.smartclassroom.enums.BorrowStatusEnum;
import com.example.smartclassroom.enums.UserType;
import com.example.smartclassroom.util.JsonDate;
import com.example.smartclassroom.util.Jwtutils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

/**
 * 拦截器配置
 */

@Slf4j
public class InterceptController implements HandlerInterceptor {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 线程局部变量保存用户登录信息
     */
    public static ThreadLocal<LoginDTO> loginUser = new ThreadLocal<>();

    /**
     * 前置拦截器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String accessToken = request.getHeader("token");
        if (!StringUtil.notNullNorEmpty(accessToken)) {
            //获取token
            accessToken = request.getParameter("token");
        }
        //没有token
        if (!StringUtil.notNullNorEmpty(accessToken)) {
            String Json = objectMapper.writeValueAsString(JsonDate.errorEnum(BorrowStatusEnum.NOT_LOGIN_PLEASE_LOGIN));
            log.error("accessToken为空");
            returnError(response, Json);
            return false;
        }
        //进行token解密
        Claims claims = Jwtutils.getJwt(accessToken);
        //token过期或者token不正确
        if (claims == null) {
            //token过期了
            String Json = objectMapper.writeValueAsString(JsonDate.success(BorrowStatusEnum.TOKEN_EXPIRE));
            log.error("accessToken过期了");
            returnError(response, Json);
            return false;
        }
        LoginDTO logInVo = LoginDTO.builder().
                loginId(Integer.valueOf(claims.get("logInId").toString()))
                .userName(String.valueOf(claims.get("userName").toString()))
                .userType(UserType.valueOf(claims.get("userType").toString()))
                        .build();
        loginUser.set(logInVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private void returnError(HttpServletResponse response, String json) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.write(json);
            printWriter.flush();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
